筆者非本科系24歲,過去沒有上過正式程式課程的經驗。買了堂線上程式課後決定來寫codewars練習,參加鐵人賽紀錄我學習的日常,長期目標是未來能從0開始做一款自己想做的遊戲。目前用python做一些基礎的程式練習,之後打算學習C#跟Unity。
希望各位前輩可以不吝嗇留言指教,若有一同學習的小夥伴也可以留言討論,與你一同進步!
Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
For example (Input --> Output):
39 --> 3 (because 39 = 27, 27 = 14, 14 = 4 and 4 has only one digit)
999 --> 4 (because 999 = 729, 729 = 126, 126 = 12, and finally 12 = 2)
4 --> 0 (because 4 is already a one-digit number)
題目理解:把數字n的每一位數視為獨立數字相乘並產生一個新數字,將這個過程記錄為一次。若新數字非個位數則再執行一次過程,記錄需要幾次此過程才能將數字n變成個位數。
(以下用Python解題)
def persistence(n):
if n < 10:
return 0
num = n
per = 0
while num/10 >= 1:
#每次都重新將數字num拆解成list用於計算
numlst =[int(i) for i in str(num)]
new_num = 1
for i in numlst:
new_num = new_num*i
num = new_num
per += 1
return per